package com.alibaba.algo.components.yapi.handler;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.stereotype.Component;

import com.alibaba.algo.components.yapi.annotations.ApiModelProperty;
import com.alibaba.algo.components.yapi.entity.Node;
import com.alibaba.algo.components.yapi.util.ClazzUtils;
import com.alibaba.algo.components.yapi.vo.ReqQuery;
import com.alibaba.algo.components.yapi.vo.RequestHandlerResponseVO;
import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class QueryRequestHandler implements RequestHandler {
	@Override
	public RequestHandlerResponseVO handler(Method method) {
		RequestHandlerResponseVO responseVO = new RequestHandlerResponseVO();
		List<ReqQuery> reqQueryList = new ArrayList<ReqQuery>();
		Parameter[] params = method.getParameters();
		if (params != null && params.length > 0) {
			for (Parameter parameter : params) {
				Class<?> modelClass = parameter.getType();
				if (ClazzUtils.simpleClass(modelClass)) {
					ReqQuery reqQuery = new ReqQuery();
					reqQuery.setName(modelClass.getSimpleName());
					reqQuery.setRequired(0);
					// 获取参数注解
					ApiModelProperty apiModelProperty = parameter.getAnnotation(ApiModelProperty.class);
					if (apiModelProperty != null) {
						reqQuery.setDesc(apiModelProperty.value());
						reqQuery.setRequired(apiModelProperty.required() == true ? 1 : 0);
						reqQuery.setExample(apiModelProperty.example());
					}
					reqQueryList.add(reqQuery);
				} else {
					List<Node> nodeList = ClazzUtils.getChildrenNodes(modelClass, new HashMap<String, String>());
					log.info("nodeList:{}", JSON.toJSONString(nodeList));
					for (Node node : nodeList) {
						ReqQuery reqQuery = new ReqQuery();
						reqQuery.setName(node.getFieldName());
						reqQuery.setRequired(node.isRequired() == true ? 1 : 0);
						reqQuery.setDesc(node.getDesc());
						reqQueryList.add(reqQuery);
					}
				}
			}
		}
		responseVO.setReqQuery(reqQueryList);
		responseVO.setMethodUri(ClazzUtils.getMethodUri(method));
		responseVO.setMethodType("GET");
		return responseVO;
	}

}
